/**
* @author Meng Zhang
**/

#include "ConfigManager.h"
#include "tinyxml/tinyxml.h"

void ConfigManager::Initialize( IPluginFacade* Cine ) {
	cine = Cine;
	WIN32_FIND_DATAA fileData;
	HANDLE hSearch;
	BOOL finished = FALSE;

	char cpath[MAX_PATH],find[MAX_PATH];
	GetCurrentDirectoryA(MAX_PATH,find);
	strcpy(cpath,find);
	strcat(cpath,"\\Config\\");
	strcat(find,"\\Config\\*.xml");
	hSearch = FindFirstFileA(find,&fileData);
	if (hSearch == INVALID_HANDLE_VALUE) {
		assert(0);
	}

	while (!finished) {
		std::string path = std::string(cpath) + fileData.cFileName;
		TiXmlDocument doc(path.c_str());
		doc.LoadFile();
		TiXmlElement *root = doc.RootElement();
		TiXmlNode *child = NULL;
		while (child = root->IterateChildren(child)) {
			if (strcmp(child->Value(),"extension")==0)
				files[child->FirstChild()->Value()] = path;
		}

		if (!FindNextFileA(hSearch,   &fileData)) {
			finished = TRUE;
		}
	}
}

void ConfigManager::Release() {
}

void ConfigManager::Activate() {
	cine->AttachListener(Events::RetrieveConfigInfoEvent::type(),this);
}

void ConfigManager::Deactivate() {
	cine->ReleaseListener(this);
}

bool ConfigManager::HandleEvent( Events::Event * ee ) {
	if (ee->GetType()==Events::RetrieveConfigInfoEvent::type()) {
		Events::RetrieveConfigInfoEvent *e = (Events::RetrieveConfigInfoEvent*)ee;
		std::map<std::string,std::string>::iterator iter = files.find(e->fileType);
		if (iter!=files.end()) {
			e->configFile = iter->second;
		} else e->configFile = files["default"];
		return true;
	}
	return false;
}